package oj.hot100;

public class 合并两个有序链表 {
    public class ListNode {
          int val;
          ListNode next;
          ListNode() {}
          ListNode(int val) { this.val = val; }
          ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode cur1 = list1,cur2 = list2;
        ListNode newHead = new ListNode(-1);//创建一个虚拟头节点,如果直接等于null的话后续的逻辑会出现空指针异常
        ListNode cur = newHead;
        while(cur1 != null && cur2 != null) {
            if(cur1.val <= cur2.val) {
                cur.next = cur1;
                cur1 = cur1.next;
            }else {
                cur.next = cur2;
                cur2 = cur2.next;
            }
            cur = cur.next;//每连接一个节点,记得往后走一步.
        }
        if(cur1 != null) {
            cur.next = cur1;
        }
        if(cur2 != null) {
            cur.next = cur2;
        }
        return newHead.next;
    }
}
